/**
 * 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
 *
 * Find the sum of all numbers which are equal to the sum of the factorial of
 * their digits.
 *
 * Note: as 1! = 1 and 2! = 2 are not sums they are not included.
 *
 */

 BigInteger fact(n) {
    switch (n) {
        case 0..1: return 1
        case 2: return 2
        case 3: return 6
        case 4: return 24
        case 5: return 120
        case 6: return 720
        case 7: return 5040
        case 8: return 40320
        case 9: return 362880
    }
    (10..n).inject(fact(9)) { result, num -> result *= num }
}

BigInteger sumOfFact(BigInteger n) {
    sum = 0
    while (n > 0) {
        sum += fact(n.mod(10))
        n = n.intdiv(10)
    }
    sum
}

boolean isCurious(BigInteger n) {
    n == sumOfFact(n)
}

assert isCurious(145)

curiousNumbers = (3..50000).inject([]) { list, n ->
    if (isCurious(n)) { list << n } else list
}
answer = curiousNumbers.sum()

println """
The numbers that are equal to the sum of the factorial of their digits are: $curiousNumbers
Their sum is (drumroll, please): $answer
"""

println fact(14)
